package com.briup.bms.service.impl;

import com.briup.bms.bean.SOrd;
import com.briup.bms.common.exceptions.BmsServiceException;
import com.briup.bms.common.utils.EntityUtils;
import com.briup.bms.common.utils.ResultCode;
import com.briup.bms.dao.IEmpMapper;
import com.briup.bms.dao.SCustomerMapper;
import com.briup.bms.dao.SOrdMapper;
import com.briup.bms.service.SOrderService;
import com.briup.bms.web.vm.OrderVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author: Paocha
 * @date: 2021-11-23-17:00
 */
@Service
public class OrderServiceImpl implements SOrderService {

    private final SOrdMapper sOrdMapper;
    private final SCustomerMapper customerMapper;
    private final IEmpMapper empMapper;

    public OrderServiceImpl(SOrdMapper sOrdMapper, SCustomerMapper customerMapper, IEmpMapper empMapper) {
        this.sOrdMapper = sOrdMapper;
        this.customerMapper = customerMapper;
        this.empMapper = empMapper;
    }

    @Override
    public PageInfo<OrderVo> findByConditon(int pageNum, int pageSize, String name) {
        PageHelper.startPage(pageNum, pageSize);
        name = (name == null || "".equals(name)) ? name : "%" + name + "%";
        List<OrderVo> sOrds = sOrdMapper.selectByCondition(name);
        return new PageInfo<>(sOrds);
    }

    @Override
    public PageInfo<OrderVo> findByPageHelper(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<OrderVo> sOrds = sOrdMapper.selectAll();
        return new PageInfo<>(sOrds);
    }

    @Override
    public void saveOrUpdate(OrderVo orderVo) {
        SOrd ord = EntityUtils.toEntity(orderVo, SOrd.class);

        if (orderVo.getId() != null) {
            //更新
            sOrdMapper.updateByPrimaryKey(ord);
        } else {
            //保存
            Integer cid=customerMapper.selectByName(orderVo.getCustomer()).getId();
            if (cid==null){
                throw new BmsServiceException(ResultCode.CUSTOMER_EXIST,"客户不存在");
            }else {
                ord.setCustomerId(cid);
                sOrdMapper.insert(ord);
            }
        }
    }

    @Override
    public void deleteOrder(Integer orderId) {
        SOrd ord = sOrdMapper.selectByPrimaryKey(orderId);
        if (ObjectUtils.isEmpty(ord)) {
            throw new BmsServiceException(ResultCode.DATA_NOT_EXIST, "数据不存在");
        }
        sOrdMapper.deleteByPrimaryKey(orderId);
    }

    @Override
    public void batchDeleteOrder(Integer[] orderIds) {
        sOrdMapper.batchDelete(orderIds);
    }
}
